import styles from "./index.module.scss"
// import { Link } from "react-router-dom"
import { HomeOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { useDispatch, useSelector } from "react-redux"
import { useEffect, useState, useRef } from "react"
import { getChannelList, getArticleList } from "@/store/actions/article"
import Channels from "@/compontes/Channels"
import { STATUS } from "@/constatnts"
import {
  Button,
  Form,
  Radio,
  Select,
  DatePicker,
  Tag,
  Card,
  Table,
  Breadcrumb,
  Image,
  Popconfirm,
  message,
} from "antd"
import { delArticle } from "../../store/actions/article"
import { useHistory } from "react-router-dom"
// import { useChannels } from "@/hooks"

const Article = () => {
  const disPatch = useDispatch()
  const params = useRef({}) //分页列表数据请求参数
  const history = useHistory()

  const loading = useSelector((state) => state.loading.loading) //异步loading效果

  //获取频道筛选初始值
  // const channels = useSelector((state) => {
  //   return state.actricle.channels
  // })
  // const channels = useChannels()

  //获取文章列表
  const articleObj = useSelector((state) => {
    return state.actricle.articles
  })

  //分页相关操作
  const onShowSizeChange = (current, pageSize) => {
    setPagination({
      ...pagination,
      current,
      pageSize,
    })
    console.log(current, pageSize)
  }

  const onChange = (page, pageSize) => {
    console.log("Page: ", page)
    setPagination({
      ...pagination,
      current: page,
    })
    params.current.page = page
    params.current.per_page = pageSize
    disPatch(getArticleList(params.current))
  }

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    position: ["bottomCenter"],
    showSizeChanger: true,
    total: 50,
    onShowSizeChange,
    onChange,
  })

  // useEffect(() => {
  //   disPatch(getChannelList())
  // }, [disPatch])

  useEffect(() => {
    disPatch(getArticleList())
  }, [disPatch])

  useEffect(() => {
    setPagination({
      ...pagination,
      total: articleObj.total_count,
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [articleObj])

  //提交表单
  const onFinish = (values) => {
    //不是全部
    if (values.status !== -1) {
      params.current.status = values.status
    } else {
      params.current.status = ""
    }
    params.current.channel_id = values.channel_id
    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss")
      params.current.end_pubdate = values.date[1]
        .endOf("day")
        .format("YYYY-MM-DD HH:mm:ss")
    }
    console.log("params", params)
    params.current.page = 1
    disPatch(getArticleList(params.current))
  }

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo)
  }

  const { RangePicker } = DatePicker
  // 本地加载图片的方式
  const img = require("@/assets/error.png")

  //文章删除操作
  const delArtFn = async (id) => {
    await disPatch(delArticle(id))
    await disPatch(getArticleList(params.current))
    message.success("删除成功")
  }

  //表格数据
  const dataSource =
    articleObj.results &&
    articleObj.results.map((item) => {
      return {
        ...item,
        cover: item.cover.type === 0 ? img : item.cover.images[0],
      }
    })

  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      key: "cover",
      render: (cover) => (
        <Image alt="" src={cover} style={{ width: "200px" }} fallback={img} />
      ),
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        const obj = STATUS.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.title}</Tag>
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
      key: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
      key: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
      key: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
      key: "like_count",
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "caozuo",
      render: (id) => (
        <div>
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            onClick={() => history.push(`/home/publish/${id}`)}
            style={{ marginRight: "20px" }}
          ></Button>
          <Popconfirm
            title="确定要删除该文章吗？"
            onConfirm={() => delArtFn(id)}
          >
            <Button danger shape="circle" icon={<DeleteOutlined />}></Button>
          </Popconfirm>
        </div>
      ),
    },
  ]

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb
            items={[
              {
                href: "/home",
                title: (
                  <>
                    <HomeOutlined />
                    <span>首页</span>
                  </>
                ),
              },
              {
                title: "文章列表",
              },
            ]}
          ></Breadcrumb>
        }
      >
        <Form
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 1000,
          }}
          initialValues={{
            status: -1,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio value={item.id} key={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channels">
            {/* <Select>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.name}>
                  {item.name}
                </Select.Option>
              ))}
            </Select> */}
            <Channels />
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
            key="sx"
          >
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={`根据筛选条件共查询到${articleObj.total_count}条结果:`}
        style={{ marginTop: 10 }}
      >
        <Table
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
          pagination={pagination}
          loading={loading}
        />
      </Card>
    </div>
  )
}

export default Article
